package com.jokerku.mini.schedule.leader;

import com.jokerku.mini.schedule.common.Constants;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author: guzq
 * @CreateTime: 2023/06/01 21:44
 * @Description: 主节点选举
 * @Version: 1.0
 */
public class LeaderShipSelector {

    private static final Logger logger = LoggerFactory.getLogger(LeaderShipSelector.class);

    private CuratorFramework client;
    private String path;
    private LeaderExecutionCallback callback;

    public LeaderShipSelector(CuratorFramework client, String path, LeaderExecutionCallback callback) {
        this.client = client;
        this.path = path;
        this.callback = callback;
    }

    public void select() throws Exception {
        try (LeaderLatch leaderLatch = new LeaderLatch(this.client, this.path)) {
            // leaderLatch.addListener(new ILeaderLatchListener());
            leaderLatch.start();
            leaderLatch.await();
            callback.callback();
        }
    }


    static class ILeaderLatchListener implements LeaderLatchListener {
        @Override
        public void isLeader() {
            logger.info("当前 {} 成为了主节点", Constants.Global.ip);
        }

        @Override
        public void notLeader() {
            logger.info("当前 {} 成为了从节点", Constants.Global.ip);
        }
    }
}
